"""
Various methods for aggregating data.
"""
import logging

import log_setup

def list_items():
    """ Dummy method used to trigger dict_aggregate() on items in a list. """
    raise Exception('This should never be called directly.')

def for_every(n, method):
    """
    Decorator: Apply method to n number if items.
    EXAMPLE:
        for_every(5, average)
        
    Returns a method for calculating averages for every 5 items.    
    """
    def new_method(series):
        if len(series) < 1:
            return []
        portion = series[:n]
        remainder = series[n:]
        results = method(portion)
        if type(results) is not list:
            results = [ results ]
        if len(remainder) > 0:
            remainder_results = new_method(remainder)
            if type(remainder_results) is not list:
                remainder_results = [ remainder_results ]
            results.extend(remainder_results)
        return results
    return new_method
    
def index_on(key, method):
    """
    Index items on key when passing to method.
    """
    #NOTE: I'm not even sure this will work. But it's a vague idea.    
    #TODO

def passthru(data):
    """
    EXAMPLE METHOD.
    Returns data with no change.
    This method is a degenerate case, provided here only as an example.
    You should define your own methods, or use those provided in the
    'methods' module.
    """
    logging.debug('Passthru: %s' % data)
    return data
    
def average(series):
    if len(series) < 1:
        return []
    else:
        return sum(series)/len(series)
    
def first(series):
    if len(series) < 1:
        return []
    else:
        return series[0]
    
def last(series):
    if len(series) < 1:
        return []
    else:
        return series[-1]    
        
#def agg_list_items(series):
#    """
#    Aggregate items in series individually.
#    """
#    from core import dict_aggregate # avoid circular imports
#    tmp = []
#    for item in series:
#        tmp.append(dict_aggregate(item))
#    return tmp
